<?php

namespace App\Http\Controllers;

use App\Http\Requests\ArticleRequest;
use App\Article;
use Auth;
use Storage;
use Str;
use Avatar;
use Illuminate\Http\Request;
use App\Handlers\ImageUploadHandler;
use App\Category;
use Mews\Purifier\Facades\Purifier;
class ArticlesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Article $article)
    {
        $articles = $article->latest()->paginate(10);
        return view('articles.index', compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Article $article)
    {
        $categories = Category::with('children')->root()->get();
        return view('articles.create_and_edit', compact('article', 'categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Article $article, ArticleRequest $request)
    {
        $article->fill($request->all());

        $article->founder_id = Auth::user()->id;
        $article->save();

        $article->refreshCache();

        return redirect()->route('articles.show', $article)->with('success', '发布成功！');
    }

    public function set(Article $article, Request $request)
    {
        $type = $request->type;
        if (in_array($type, ['excellent', 'pinned', 'frozen', 'banned'])) {
            echo $type . '_at';
            if(!$article->getAttribute($type . '_at')) {
                $article->update([
                    $type . '_at' => now()
                ]);
            } else {
                $article->update([
                    $type . '_at' => null
                ]);
            }
        }
        return redirect()->back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article, $version = null)
    {
        if ($version) {
            $version = $article->version($version);
        } else {
            $version = $article->version();
        }
        $article->load('comments');
        $article->load('versions');
        // dd($article->versions);
        $article->update(['cache->views_count' => $article->cache['views_count'] + 1]);
        return view('articles.show', compact('article', 'version'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article)
    {
        $version = $article->version();
        $categories = Category::with('children')->root()->get();
        $version->loadMissing('content');
        return view('articles.create_and_edit', compact('article', 'categories', 'version'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Article $article, ArticleRequest $request)
    {
        // 需要作为副本保存
        $oldArticle = $article->version();
        $oldCategories = $oldArticle->categories->pluck('id')->toArray();
        $oldArticle->loadMissing('content');
        $newArticle = new Article;
        $newArticle->fill($request->all());
        // 处理一下提交的 分类 字符串
        $requestCategory = explode(',', $request->category);
        $newCategories = collect($requestCategory)->map(function ($i, $key) {
            return (int) $i;
        })->toArray();
        // 先判断是否有变化
        $titleChange = $oldArticle->title !== $newArticle->title;
        $contentChange = $oldArticle->content->body !== Purifier::clean($request->body);
        $categoryChange = $oldCategories !== $newCategories;
        if (!$titleChange && !$contentChange && !$categoryChange) {
            return redirect()->route('articles.edit', $article)->with('warning', ' 没有做任何修改！');
        }

        $newArticle->founder_id = $oldArticle->founder_id;
        $newArticle->article_id = $oldArticle->id;

        $newArticle->save();
        // 做一些简单的记录

        $newArticle->loadMissing('content');

        $newCategories = $newArticle->categories->pluck('id')->toArray();
        dump($oldCategories);
        dump($newCategories);
        dump('是否移除了标签');
        dump(array_diff($oldCategories, $newCategories));

        dump('是否添加了标签');
        dump(array_diff($newCategories, $oldCategories));

        dump($oldArticle->content->body);
        dd($newArticle->content->body);
        return redirect()->route('articles.show', $article)->with('success', '修改成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
        // 初始化返回数据，默认是失败的
        $data = [
            'success'   => false,
            'msg'       => '上传失败!',
            'file_path' => ''
        ];
        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploader->save($request->upload_file, 'topics', \Auth::id(), 1024);
            // 图片保存成功的话
            if ($result) {
                $data['file_path'] = $result['path'];
                $data['msg']       = "上传成功!";
                $data['success']   = true;
            }
        }
        return $data;
    }
}
